package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.serve.dto.AlertDataPageReqDto;
import com.zzyl.system.mapper.SysUserMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author iteheima
 * @date 2025-03-18
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 处理报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public void updateAlertData(AlertData alertData) {
        AlertData alertData1 = BeanUtil.copyProperties(alertData, AlertData.class);
        String iotId = alertDataMapper.selectIotIdById(alertData.getId());
        alertData1.setIotId(iotId);
        Date createTime = alertDataMapper.selectCreateTimeById(alertData.getId());
        alertData1.setCreateTime(createTime);
        if (alertData.getProcessingTime().isAfter(LocalDateTime.now()) || alertData.getProcessingTime().isBefore(LocalDateTime.ofInstant(alertData1.getCreateTime().toInstant(), ZoneId.systemDefault()))) {
            throw new RuntimeException("处理时间不能早于异常数据产生时间或者不能晚于当前时间");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        String processorName = sysUserMapper.getNameByUserId(userId);
        alertData1.setProcessorName(processorName);
        alertData1.setStatus(1);
        alertDataMapper.updateById(alertData1);
        LambdaQueryWrapper<AlertData> queryWrapper = new LambdaQueryWrapper<AlertData>()
                .eq(AlertData::getIotId, alertData1.getIotId())
                .eq(AlertData::getCreateTime, alertData1.getCreateTime())
                .eq(AlertData::getStatus, 0);
        AlertData one = this.getOne(queryWrapper);
        one.setProcessorName(processorName);
        one.setProcessingTime(alertData1.getProcessingTime());
        one.setStatus(1);
        alertDataMapper.updateById(one);
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public List<AlertData> pagelist(AlertDataPageReqDto dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        List<AlertData> list = this.list(new LambdaQueryWrapper<AlertData>()
                .eq(StrUtil.isNotBlank(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
                .eq(userId != null, AlertData::getUserId, userId)
                .between(ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime()),
                        AlertData::getCreateTime,
                        dto.getStartTime(),
                        dto.getEndTime()
                )
                .eq(ObjectUtil.isNotEmpty(dto.getStatus()), AlertData::getStatus, dto.getStatus())
        );

        return list;
    }
}
